//
// Created by none98 on 2021/9/10.
//

#include <vector>
#include "Selector.h"
#include "Channel.h"
#include <sys/epoll.h>

int Selector::RegisterChannel(Channel *channel) {
    struct epoll_event event;
    event.events=channel->interestedEvents;
    event.data.ptr=channel;
    return epoll_ctl(fd,EPOLL_CTL_ADD,channel->GetFd(),&event);
}

int Selector::UpdateChannel(Channel *channel) {
    struct epoll_event event;
    event.events=channel->interestedEvents;
    event.data.ptr=channel;
    return epoll_ctl(fd,EPOLL_CTL_MOD,channel->GetFd(),&event);
}

int Selector::DeleteChannel(Channel *channel) {
    return 0;
}

std::vector<Channel*> Selector::Select(int timeout) {
    std::vector<Channel*> vec;
    struct epoll_event events[65535];
    int rsize = epoll_wait(fd, events, 65535, timeout);
    for(int i=0; i<rsize; i++){
        Channel *channel= static_cast<Channel*>(events[i].data.ptr);
        channel->activeEvents=events[i].events;
        vec.push_back(channel);
    }
    return std::move(vec);
}

